package queue;

import java.util.Date;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * 同步队列Demo
 */
public class SynchronousQueueDemo {
    public static void main(String[] args) {
        //同步队列
        SynchronousQueue<String> synchronousQueue = new SynchronousQueue<String>();

        //存元素
        new Thread(()->{
            try {
                for(int i = 0 ; i < 3 ; i++) {
                    System.out.println(Thread.currentThread().getName() + " put " + (i + 1) + " = " + new Date());
                    synchronousQueue.put(String.valueOf(i + 1));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();



        //取元素
        new Thread(()->{
            try {
                for(int i = 0 ; i < 3 ; i++) {
                    TimeUnit.SECONDS.sleep(3);
                    System.out.println(Thread.currentThread().getName() + " take " + (i + 1) + " = " + new Date());
                    System.out.println(synchronousQueue.take());
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }).start();
    }
}
